using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using AlgorithmsVisualized.Components;
using System.Collections.ObjectModel;
//using AlgorithmsVisualized.Controls;
using GraphConstructor;
using System.IO;

namespace AlgorithmsVisualized
{
    public class AssemblyLoader
    {
        private List<IGraph> _objects = new List<IGraph>();
        private List<string> _classNames = new List<string>();

        public ReadOnlyCollection<string> ClassNames
        {
            get { return _classNames.AsReadOnly(); }
        }

        public ReadOnlyCollection<IGraph> Objects
        {
            get { return _objects.AsReadOnly(); }
        }

        public void LoadAssemblies(string path)
        {
            string[] files = Directory.GetFiles(path);

            foreach (string fileName in files)
            {
                Assembly assem = Assembly.LoadFrom(fileName);

                Type[] types = assem.GetTypes();

                foreach (Type t in types)
                {
                    if (t.IsClass)
                    {
                        VisualAlgorithm[] attributes = (VisualAlgorithm[])t.GetCustomAttributes(typeof(VisualAlgorithm), false);
                        Type[] filtered = t.FindInterfaces(FilterVisualAlgorithm, null);
                        if (filtered.Length != 0)
                        {
                            _objects.Add((IGraph)(Activator.CreateInstance(t)));
                            _classNames.Add(t.Name);
                        }
                    }
                }
            }
        }
        public void Reset()
        {
            _objects.Clear();
            _classNames.Clear();
        }
        bool FilterVisualAlgorithm(Type t, object obj)
        {
            return t == typeof(IGraph);
        }
    }
}
